// pages/main/main.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    datas: [],
    poster: "http://pic.qiantucdn.com/58pic/32/73/24/04r58PIC7N35Fi5ca5YQc_PIC2018.png!qtwebp324",
    audioId: "myAudio",
    currentIndex: 0,
    currentItem: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.data.datas = app.datas;
    this.audioCtx = wx.createAudioContext(this.data.audioId)
    this.setData({
      currentItem: this.data.datas[this.data.currentIndex]
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  playAudio: function(e) {
    this.audioCtx.setSrc(app.englishWordAudioUrl(this.data.datas[this.data.currentIndex].english))
    this.audioCtx.play();
  },

  nextData: function(curIndex) {
    let strategy = app.getStrategy();
    let length = this.data.datas.length;
    if (strategy == "asc") {
      if (curIndex >= 0 && curIndex < length - 1) {
        return [curIndex + 1, this.data.datas[curIndex + 1]];
      } else {
        return [0, this.data.datas[0]];
      }
    } else {
      let next = Math.floor((Math.random() * length))
      return [next, this.data.datas[next]];
    }
  },
  prevData: function(curIndex) {
    let strategy = app.getStrategy();
    let length = this.data.datas.length;
    if (strategy == "asc") {
      if (curIndex >= 1) {
        return [curIndex - 1, this.data.datas[curIndex - 1]];
      } else {
        return [length - 1, this.data.datas[length - 1]];
      }
    } else {
      let next = Math.floor((Math.random() * length))
      return [next, this.data.datas[next]];
    }
  },


  prev: function() {
    let index = this.data.currentIndex;
    let prev = this.prevData(index);
    this.setData({
      currentIndex: prev[0],
      currentItem: prev[1]
    })
  },
  next: function() {
    let index = this.data.currentIndex;
    let next = this.nextData(index);
    this.setData({
      currentIndex: next[0],
      currentItem: next[1]
    })


  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})